<?php
namespace Admin\Controller;
use Think\Controller;
/**
 * 产品管理
 */
class ProductController extends BaseController
{
    /**
     * 列表
     * @return [type] [description]
     */
    public function index($key="")
    {
        if($key === ""){
            $model = D('ProductView'); 
        }else{
            $where['product.name'] = array('like',"%$key%");
            $where['category.name'] = array('like',"%$key%");
            $where['_logic'] = 'or';
            $model = D('ProductView')->where($where); 
        } 

        $count  = $model->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)

        $Page -> setConfig('prev','«');
        $Page -> setConfig('next','»');
        //$Page -> setConfig('theme',"<div class='defaultPager'>%UP_PAGE% %LINK_PAGE% %DOWN_PAGE%</div>");
        $Page -> setConfig('theme',"<ul class='pagination pagination-sm no-margin'> <li>%UP_PAGE%</li>  <li>%LINK_PAGE%</li>   <li>%DOWN_PAGE%</li>  </ul>");
        $show = $Page->show();// 分页显示输出
        $post = $model->limit($Page->firstRow.','.$Page->listRows)->where($where)->order('product.order_number DESC,product.id DESC')->select();

        $this->assign('post', $post);
        $this->assign('page',$show);
        $this->display();     
    }
    
    /**
     * 添加
     */
    public function add()
    {
        //默认显示添加表单
        if (!IS_POST) {
        	$nav=D('Category')->getTreeData('tree','order_number,id');
            
            $this->assign('nav',$nav);
            $this->display();
        }
        if (IS_POST) {
            //日期格式  月/日/年 10/06/2016
            $push_time = I('post.time');

            $year=((int)substr($push_time,6,4));//取得年份

            $day=((int)substr($push_time,3,2));//取得月份

            $month=((int)substr($push_time,0,2));//取得月份

            $time_str = mktime(0,0,0,$month,$day,$year);

             //date("Y/m/d",$time_str);  

            //如果用户提交数据
            $model = D("Product"); //用D操作，自动验证
            $info = $model->create();
            if (!$info) {
                $this->error($model->getError());
            }
            $info['time'] = $time_str;

            /*$thumb = $_FILES['thumb'];
            if ($thumb['name'] != '') {
                $thumbpath = $this->uploadoneimg($thumb);
                $thumbpath = $thumbpath['savepath'].$thumbpath['savename'];
                $info['thumb'] = $thumbpath;
            }*/

            //上传图片函数
            $photo = $_FILES['photo']['name'][0];
            if ($photo != '') {
                $photo = $this->uploadimg();
                foreach ($photo as $value) { //图片处理
                    $photopath .= $value['savepath'].$value['savename'].',';
                }
                $photopath = rtrim($photopath,",");
                $info['photo'] = $photopath;
            }

            $result = $model->data($info)->add();
            if ($result) {
                $this->success("添加成功", U('product/index'));
            } else {
                $this->error("添加失败");
            } 
        }
    }

    /**
     * 复制
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function copy($id)
    {
        $id = intval($id);
        $info = M('product')->where("id= %d",$id)->find();

        //重组数据
        unset($info['id']);

        //复制的时候暂时除去标签
        unset($info['tags']);


        if ($info['photo']) {
            $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
            $photopath = '';

            $photo = explode(',',$info['photo']);
            
            foreach ($photo as $key=>$value) {
                $source = $value;

                $destination = strstr($value, '/',true).'/' .$key.time().strstr($value, '.');

                copy($path.$source , $path.$destination);
                $photopath .= $destination.',';
            }
            $photopath = rtrim($photopath,",");
            $info['photo'] = $photopath;
        }



        if (M('product')->data($info)->add()) {
            $this->success("复制成功", U('product/index'));
        } else {
            $this->error("复制失败");
        } 
    }

    /**
     * 更新信息
     * @param  [type] $id [文章ID]
     * @return [type]     [description]
     */
    public function edit($id)
    {
    	$id = intval($id);
        //默认显示添加表单
        if (!IS_POST) {
            $nav=D('Category')->getTreeData('tree','order_number,id');
            $data=M('product')->find($id);

            if (!empty($data['photo']) ) {
                $photo = explode(',',$data['photo']);
                $this->assign('photo',$photo);
            }

            $this->assign('nav',$nav);
            $this->assign('data',$data);
            $this->assign('thumb',$data['thumb']);
            $this->display();
        }
        if (IS_POST) {
            $model = D("Product");

            $info = $model->create();
            if (!$info) {
                $this->error($model->getError());
            }

            //日期格式  月/日/年 10/06/2016
            $push_time = I('post.time');

            $year=((int)substr($push_time,6,4));//取得年份

            $day=((int)substr($push_time,3,2));//取得月份

            $month=((int)substr($push_time,0,2));//取得月份

            $time_str = mktime(0,0,0,$month,$day,$year);

             //date("Y/m/d",$time_str); 

             $info['time'] = $time_str; 


            /*$thumb = $_FILES['thumb'];
            if ($thumb['name'] != '') {
                $thumbpath = $this->uploadoneimg($thumb);
                $thumbpath = $thumbpath['savepath'].$thumbpath['savename'];
                $info['thumb'] = $thumbpath;
            }*/

            $photoExist = implode(",", I('post.photoexist')); //取出以存在或经过排序的图片
            //上传图片函数
            $photo = $_FILES['photo']['name'][0];
            if ($photo != '') {
                $photo = $this->uploadimg();
                foreach ($photo as $value) { //图片处理
                    $photopath .= $value['savepath'].$value['savename'].',';
                }
                $photoLast = rtrim($photopath,","); 
                if ($photoExist) {
                    $info['photo'] = $photoExist.','.$photoLast;//如果存在旧图,旧图加新图
                } else {
                    $info['photo'] =$photoLast;//不存在旧图，直接存新图
                }
            }  else { //如果没有新提交图片，原图片不变
                $info['photo'] = $photoExist;
            }

           
            if ($model->save($info)) {
                $this->success("更新成功");
            } else {
                $this->error("更新失败");
            }          
        }
    }

    /**
     * 删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete($id)
    {
        $id = intval($id);
        $model = M('product');

        //处理多图   
        $photo = $model->where("id= %d",$id)->getField('photo');   
        $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';

        delallimg($path,$photo);//删除图片，包括文件路径
                
        $result = $model->where("id= %d",$id)->delete();
        if($result){
            $this->success("删除成功", U('product/index'));
        }else{
            $this->error("删除失败");
        }
    }

    /**
     * 删除文章缩略图
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delthumb() {
        $id = intval(I('get.id'));
        if ($id) {
            $map['id'] = $id;
            $model=M('product');
            $thumb = $model->where($map)->getField('thumb');
            $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
            delallimg($path,$thumb); //删除图片，包括文件路径
            if ($model->where($map)->setField('thumb','')) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }

    /**
     * 删除所选的文章
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delAll() {   //ajax删除选中的新闻   
        $id = array();
        $id = I('post.new_id'); 
        $new_id = implode(',',$id);
        $model = M('product');

        foreach ($id as $value) { //删除所选的图片路径
            $where['id'] = $value;

            //获取多图
            $photo=$model->where($where)->getField('photo');
            if ($photo) {
                $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
                delallimg($path,$photo);
            }
        }

        $map['id']  = array('in',$new_id);
        $result = $model->where($map)->delete();
        if ($result) {
            $this->ajaxReturn("删除成功");
        }  else {
            $this->ajaxReturn("删除失败");  
        }         
    }

    /**
     * 排序
     */
    public function order(){
        $data=I('post.');
        D('Product')->orderData($data);
        $this->success('排序成功',U('Admin/product/index'));
    }


    //删除多图的单张图片
    public function deletePhoto() {
        $name = I('get.name');

        $id = I('get.id');
        $field = I('get.field');
        if ($name && $id) {
            $map['id'] = $id;
            $product = M("Product");
            $photo = $product->where($map)->getField($field);

            $photo_array = explode(',', $photo);
            $k = $name-1;
            $photo_del = $photo_array[$k];
            
            unset($photo_array[$k]);

            $photo = implode(",", $photo_array);

            if ($product->where($map)->setField($field,$photo)) {
                $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';//删除图片所在的位置
                if(delallimg($path,$photo_del)){
                    $this->success('删除成功');
                }else{
                    $this->success('数据删除成功，但找不到要删除的图片');
                }
            } else {
                $this->error("删除图片失败");
            }       
        }       
    }

    //删除多图的所有图片
    public function deleteAllPhoto() {
        $id = I('get.id');
        if ($id) {
            $map['id'] = $id;
            $product=M('Product');
            $photo = $product->where($map)->getField('photo');
            $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
            delallimg($path,$photo); //删除产品所有的图片，包括文件路径
            if ($product->where($map)->setField('photo','')) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }
}
